//
//  WMH_MainTab2_ViewController.m
//  EpointFrame5
//
//  Created by AndLi on 15/4/21.
//  Copyright (c) 2015年 Epoint. All rights reserved.
//

#import "WMH_MainTab2_ViewController.h"
#import "EpointWebInfoListViewController.h"
#import "InfoListModel.h"
#import "EpointWebInfoListCell.h"
#import "MJRefresh.h"
#import "EpointWebInfoDetailViewController.h"
#import "EpointWebInfoDetailViewController_V2.h"
#import "EpointWebInfoListCellUniversalCell.h"
@interface WMH_MainTab2_ViewController ()
{
    NSMutableArray *dataArray;
    UITableView *tv;
    UISearchBar *sb;
    UISearchDisplayController *searchController;
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
    //列表索引
    int pageIndex;
    
    //每页列表数量
    int listPageCount;
    
    //搜索关键字
    NSString *keyWork;
    
    //字体大小
    double list_title_fontsize;
    double list_date_fontsize;
    //标题字数
    int list_title_length;
    
}

@end

@implementation WMH_MainTab2_ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    pageIndex = 0;
    listPageCount = 20;
    keyWork = @"";
    
    list_title_fontsize = [[DBFrameService getConfigValue:WMH_InfoList_Title_FontSize]  floatValue];
    list_date_fontsize  = [[DBFrameService getConfigValue:WMH_InfoList_Date_FontSize]   floatValue];
    list_title_length   = [[DBFrameService getConfigValue:WMH_InfoList_Title_Length]    floatValue];
    
    dataArray = [[NSMutableArray alloc]init];
    //    sb = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, AppWidth, 44)];
    //    sb.placeholder = @"关键字检索";
    //    sb.delegate = self;
    //    [self.view addSubview:sb];
    //
    //
    //    searchController = [[UISearchDisplayController alloc]initWithSearchBar:sb contentsController:self];
    //    searchController.searchResultsTableView.backgroundColor = [UIColor clearColor];
    //    searchController.searchResultsTableView.separatorColor = [UIColor clearColor];
    //    searchController.delegate = self;
    //    searchController.searchResultsDataSource = self;
    //    searchController.searchResultsDelegate = self;
    //    searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    //    searchController.searchResultsTableView.bounces = NO;
    
    tv = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, AppWidth, AppHeight-SystemTakeHeight-49)];
    tv.rowHeight = 75;
    tv.dataSource = self;
    tv.delegate = self;
    
    [self.view addSubview:tv];
    
    [self getData:pageIndex taskid:1];
    [self addHeader];
    [self addFooter];
}

- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell {
    return YES;
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:NO];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:YES];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [dataArray removeAllObjects];
    pageIndex = 1;
    keyWork = searchText;
    [self getData:pageIndex taskid:1];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    [searchBar resignFirstResponder];
    
    [searchController setActive:NO animated:YES];
}

- (void)addFooter
{
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = tv;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        pageIndex++;
        [self getData:pageIndex taskid:1];
    };
    _footer = footer;
}

-(void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = tv;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self getData:1 taskid:2];
    };
    _header = header;
}

-(void)getData:(int)_index taskid:(int)taskid
{
    [self showMBPHUD];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:[NSString stringWithFormat:@"%i",_index]          forKey:@"CurrentPageIndex"];
    [params setObject:[NSString stringWithFormat:@"%i",listPageCount]   forKey:@"PageSize"];
    [params setObject:CateNum_NEWS                                      forKey:@"CateNum"];
    [params setObject:@"0"                                              forKey:@"IsHeadNews"];
    [params setObject:@""                                               forKey:@"Title"];
    [self startTask:@"Task_GetInfoList" withParams:params withTaskId:taskid];
}

-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    [self hideMBPHUD];
    //处理异常信息
    NSMutableArray *arr = (NSMutableArray*)obj;
    if (![[arr objectAtIndex:0]isEqualToString:@"1"]) {
        [self toastMessage:[arr objectAtIndex:1]];
        [_footer endRefreshing];
        [_header endRefreshing];
        return;
    }
    
    if (taskId==1) {
        
        NSMutableArray *listData = [arr objectAtIndex:2];
        
        for (InfoListModel *m in listData) {
            [dataArray addObject:m];
        }
        [tv reloadData];
        [searchController.searchResultsTableView reloadData];
        [_footer endRefreshing];
        if (listData.count<listPageCount&&keyWork.length==0) {
            [_footer removeFromSuperview];
        }
    }
    else if (taskId==2)
    {
        NSMutableArray *listData = [arr objectAtIndex:2];
        NSMutableArray *enableData = [[NSMutableArray alloc]init];
        for (InfoListModel *m in listData) {
            InfoListModel *om = [dataArray objectAtIndex:0];
            NSString *firstInfoGuid = om.InfoID;
            if ([m.InfoID isEqualToString:firstInfoGuid]) {
                break;
            }
            else
            {
                [enableData addObject:m];
            }
        }
        for (int i=enableData.count-1; i>=0; i--) {
            InfoListModel *sm = [enableData objectAtIndex:i];
            [dataArray insertObject:sm atIndex:0];
        }
        [_header endRefreshing];
        [tv reloadData];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *WebinfolistItem = @"WMH_NewsListCell";
    WMH_NewsListCell *cell = (WMH_NewsListCell *)[tableView dequeueReusableCellWithIdentifier:WebinfolistItem];
    
    if(cell==nil){
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"WMH_NewsListCell"
                                                    owner:self
                                                  options:nil];
        cell = [nib objectAtIndex:0];
        
    }
    NSUInteger row = [indexPath row];
    InfoListModel *info = [dataArray objectAtIndex:row];
    
    cell.infoTitleLabel.text = [NSString stringWithFormat:@"%@",info.Title];
    //时间格式2013/2/20 9:00:00
    NSString *infodatestr = info.InfoDate;
    if([infodatestr rangeOfString:@"-"].location !=NSNotFound){
        NSArray *str=[infodatestr componentsSeparatedByString:@" "];
        NSArray *str2=[[str objectAtIndex:0] componentsSeparatedByString:@"-"];
        cell.infoTimeLabel.text = [NSString stringWithFormat:@"%@-%@",[str2 objectAtIndex:1],[str2 objectAtIndex:2]];
        
    }else{
        cell.infoTimeLabel.text = info.InfoDate;
    }
    
    NSString *temptitle;
    //控制标题长度
    if(info.Title.length>list_title_length){
        temptitle = [info.Title substringWithRange:NSMakeRange(0, list_title_length-1)];
        temptitle = [NSString stringWithFormat:@"%@...",temptitle];
    }else{
        temptitle = info.Title;
    }
    cell.infoTitleLabel.text = temptitle;
    
    cell.infoTitleLabel.frame = CGRectMake(2,0, 320-2, 60);
    cell.infoTimeLabel.frame =CGRectMake(320-91,30, 80, 18);
    cell.imageView.frame =CGRectMake(320-45-31-20+8,30+2, 31, 15);
    
    cell.infoTimeLabel.font=[UIFont fontWithName:wmh_listitem_font size:list_date_fontsize];
    cell.infoTitleLabel.font=[UIFont fontWithName:wmh_listitem_font size:list_title_fontsize];
    
    cell.infoTimeLabel.textColor = [UIColor grayColor];
    
    //cell.selectionStyle = UITableViewCellSelectionStyleNone;//无点击效果
    return cell;
}

- (NSArray *)rightButtons
{
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                title:@"收藏"];
    return rightUtilityButtons;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60-2;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    InfoListModel *m = [dataArray objectAtIndex:indexPath.row];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:m.InfoID      forKey:@"InfoID"];
    [params setObject:CateNum_NEWS  forKey:@"CateNum"];
    [params setObject:@"0"          forKey:@"IsNeedUrl"];
    WMH_NewsDetail_ViewController *view = [[WMH_NewsDetail_ViewController alloc]init];
    view.passParam = params;
    [self.navigationController pushViewController:view animated:YES];
}

@end

